React Hooks is an exciting new feature that allows you to do anything in components of function rather than using classes such as fetch data. A lot of discussions are going on around them, but you’re here to get information!
In this tutorial, I want to show you how to fetch data in React with Hooks by using the state and effect hooks.
Refactoring from a class to functional component
Our first step to using hooks would be to refactor it to a functional component. Remember, you use hooks only with functional components. Fetching data with the fetch API and React class component
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import React, { Component } from "react"; export default class Planets extends Component { state = { hasErrors: false, planets: {} }; componentDidMount() { fetch("https://swapi.co/api/planets/4/") .then(res => res.json()) .then(res => this.setState({ planets: res })) .catch(() => this.setState({ hasErrors: true })); } render() { return <div>{JSON.stringify(this.state.planets)}</div>; } } |
In the above code, The component has a hasError
and a planets
state. If the component mounts, we call the Starwars API and fetch the information.
Here’s how would transform the Class component to a functional component.
UseEffect is a React hook that accepts a callback as the first argument. Inside the first argument, we do all the tasks related to the effect. So, Import the useEffect
from the React package, and replace the componentWillMount
with the fresh hook.
What does useEffect
do?
By using this Hook, you tell React that after rendering, your component needs to do something. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after DOM updates have been made.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import React, { useState, useEffect } from "react"; const Planets = () => { const [hasError, setErrors] = useState(false); const [planets, setPlanets] = useState({}); useEffect(() => { async function fetchData() { const res = await fetch("https://swapi.co/api/planets/4/"); res .json() .then(res => setPlanets(res)) .catch(err => setErrors(err)); } fetchData(); }); return ( <div> <span>{JSON.stringify(planets)}</span> <hr> <span>Has error: {JSON.stringify(hasError)}</span> </div> ); }; export default Planets; |
In the above code, Hooks don’t have lifecycle effects such ascomponentDidMount
or componentWillMount
Note:- If you want the useEffect
to behave like the componentDidMount
lifecycle event, pass an array as the second argument, like so;
2 3 4 5 6 |
useEffect(() => { fetchData() }, []) |
Consider the second argument as the dependencies for that effect. The impact will run again if one of the dependencies has changed since the last time.
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co